package com.wang.webSocket;


import com.wang.conf.AppConf;
import com.wang.util.PrintUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

public class NettyWebSocketServer {

    private static final Integer serverPort = AppConf.webSocketPort;

    @PostConstruct
    public static void start() {
        PrintUtil.print("正在启动websocket服务器");
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, work);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new NettyWebSocketChannelInitializer()); //添加处理类
            Channel channel = bootstrap.bind(serverPort).sync().channel();
            PrintUtil.print("webSocket服务启动成功，端口号:" + serverPort);
            channel.closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
            PrintUtil.print("webSocket服务启动失败：" + e);
        } finally {
            boss.shutdownGracefully();
            work.shutdownGracefully();
            PrintUtil.print("websocket服务器已关闭");
        }
    }


    public static void main(String[] args) {
        new NettyWebSocketServer().start();
    }
}

